package com.tanglongan.concurrent.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class CreateThreadPoolDemo {

    public static final int SLEEP_GAP = 5;

    static class TargetTask implements Runnable {
        static AtomicInteger taskNo = new AtomicInteger(1);
        private final String taskName;

        public TargetTask() {
            this.taskName = "task-" + taskNo.get();
            taskNo.incrementAndGet();
        }

        @Override
        public void run() {
            System.out.println("任务：" + taskName + " doing");
            sleepSeconds(SLEEP_GAP);
            System.out.println(taskName + " 运行结束");
        }
    }

    private static void sleepSeconds(int l) {
        LockSupport.parkNanos(l * 1000L * 1000L * 1000L);
    }


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new TargetTask());
            executorService.submit(new TargetTask());
        }

        sleepSeconds(1000);
        executorService.shutdown();
    }
}
